import * as storage from '@/utils/storage';
// 通过user类来构造user状态值
class User {
    constructor(user) {
        // 避免user为null
        if (!user) user = {}
        this.id = user.id || -1
        this.username = user.username || ''
        this.role = user.role || ''
        this.avatar = user.avatar || ''
    }
}
const token = storage.getSessionToken() || storage.getLocalToken() || ''
const user = new User(storage.getSessionUser())

export default {
    state: () => ({
        token: token,
        user: user
    }),
    getters: {
        isLogin: (state) => state.user.id !== -1,
        isAdmin: (state) => state.user.role === 'ROLE_admin'
    },
    mutations: {
        /**
         * 设置用户的值
         * @param {*} state 
         * @param {*} user 
         */
        SET_USER(state, user) {
            state.user = new User(user)
        },
        /**
         * 设置token值
         * @param {*} state 
         * @param {*} token 
         */
        SET_TOKEN(state, token) {
            state.token = token
        }
    },
    actions: {
        /**
         * 登录成功需要设置相应状态
         * @param {*} context 
         * @param {*} data 
         */
        LoginSuccess(context, data) {

            const {
                token,
                isRememberme,
                ...user
            } = data
            context.commit('SET_TOKEN', token)
            context.commit('SET_USER', user)
                // 将用户信息与token存储到sessionStorage中
            storage.setSessionToken(token)
            storage.setSessionUser(user)
                /**
                 * 如果用户选择记住密码，则将token存储到localStorage中，
                 * 下次登录，用token获取用户信息，并跳转到首页
                 */
            if (isRememberme) {
                storage.setLocalToken(token)
            } else {
                storage.removeLocalToken()
            }
        },

        /**
         * 用户注销
         * @param {*} context 
         */
        LogoutSuccess(context) {
            context.commit('SET_TOKEN', '')
            context.commit('SET_USER', {})
            context.commit('RESET_TABS_VALUE')
            storage.removeLocalToken()
            storage.removeSessionToken()
            storage.removeSessionUser()
            storage.removeSessionTabsValue()
        },

        UpdateUser(context, user) {
            context.commit('SET_USER', user)
            const sessionUser = new User(user)
            storage.setSessionUser(sessionUser)
        }
    }
}